from django.shortcuts import render
from rest_framework import viewsets
from platefrom.models import Platefrom,Skus,SkusUser
from user.models import User,UserAccountBind
from platefrom.serializers import PlatformSerializer,SkusSerializer,SkusBindSerializer,PlatformAllSerializer
from platefrom.filter import SkusFilter
from django.db.models import Q
from utils.pagination_util import PageNumberPaginationUtil
from rest_framework.decorators import action
# api响应
from utils.response_util import APIResponse,Response,VueAPIResponse
from rest_framework import status as response_status

from server.utils import check_group_id

# Create your views here.
class IndexViewSets(viewsets.ModelViewSet):
    """接口首页 平台信息"""
    queryset = Platefrom.objects.all()
    serializer_class = PlatformSerializer

    # def get_permissions(self):
    #     """授权"""
    #     if self.action == 'list':
    #         return [permissions.IsAuthenticated()]
    #     else:
    #         return [NoAwayPermission()]

class AllPlateFromViewSets(viewsets.ModelViewSet):
    """接口首页 平台信息"""
    queryset = Platefrom.objects.all()
    serializer_class = PlatformAllSerializer
    def list(self, req, *args, **kwargs):
        # 查询除了超级管理员外的所有用户
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        return APIResponse(results=serializer.data)

    @action(methods=['get'], detail=False, url_path='by_user')
    def by_user(self, request, *args, **kwargs):
        if check_group_id(self.request.user.group_id) == 'super_admin':
            list = self.queryset.all().order_by('id')
        elif check_group_id(self.request.user.group_id) == 'company_admin':
            # 查公司用户
            user_platefrom_ids = UserAccountBind.objects.filter(company_id=self.request.user.company_id).values('platefrom_id')
            platefrom_ids = []
            for i in user_platefrom_ids:
                platefrom_ids.append(i['platefrom_id'])
            list = self.queryset.filter(id__in=platefrom_ids).order_by('id')
        elif check_group_id(self.request.user.group_id) == 'person':
            # 查个人
            user_platefrom_ids = UserAccountBind.objects.filter(user_id=self.request.user.id).values('platefrom_id')
            platefrom_ids = []
            for i in user_platefrom_ids:
                platefrom_ids.append(i['platefrom_id'])
            list = self.queryset.filter(id__in=platefrom_ids).order_by('id')
        elif check_group_id(self.request.user.group_id) == 'staff':
            user_platefrom_ids = UserAccountBind.objects.filter(company_id=self.request.user.company_id).values('platefrom_id')
            platefrom_ids = []
            for i in user_platefrom_ids:
                platefrom_ids.append(i['platefrom_id'])
            list = self.queryset.filter(id__in=platefrom_ids).order_by('id')

        serializer = self.get_serializer(list, many=True)
        return APIResponse(results=serializer.data)


class SkuViewSet(viewsets.ModelViewSet):
    """规格管理"""
    queryset = Skus.objects.exclude(id=1).order_by('order')
    serializer_class = SkusSerializer
    filterset_class = SkusFilter
    search_fields = ['title', 'labels']
    pagination_class = PageNumberPaginationUtil


    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        title = request.GET.get('title')
        if title:
            queryset = queryset.filter(
                Q(title__icontains=title))
        serializer = self.get_serializer(queryset, many=True)
        for s in serializer.data:
            platefrom = Platefrom.objects.filter(id__in=s['platefrom_ids'].split(",")).values()
            s['platefrom'] = platefrom
            s['content_type'] = s['content_type_ids'].split(",")
        return VueAPIResponse(self, queryset, data=serializer.data)

    @action(methods=['post'], detail=False, url_path='delete_all')
    def bulk_deletes(self, request, *args, **kwargs):
        ids = self.request.data['ids']
        queryset = self.get_queryset().filter(id__in=ids)
        if queryset:
            queryset.delete()
            return Response(status=response_status.HTTP_204_NO_CONTENT)
        else:
            return Response(status=response_status.HTTP_404_NOT_FOUND)

class SkusBindViewSet(viewsets.ModelViewSet):
    """规格-用户绑定管理"""
    queryset = SkusUser.objects.all()
    serializer_class = SkusBindSerializer
    pagination_class = PageNumberPaginationUtil
    def list(self, request, *args, **kwargs):
        if check_group_id(self.request.user.group_id) == 'super_admin':
            queryset = self.filter_queryset(self.get_queryset())
        elif check_group_id(self.request.user.group_id) == 'company_admin':
            # 查公司用户
            queryset = self.filter_queryset(self.get_queryset().filter(company_id=self.request.user.company_id))
        elif check_group_id(self.request.user.group_id) == 'person':
            # 查个人
            queryset = self.filter_queryset(self.get_queryset().filter(user_id=self.request.user.id))

        elif check_group_id(self.request.user.group_id) == 'staff':
            queryset = self.filter_queryset(self.get_queryset().filter(company_id=self.request.user.company_id))
        # queryset = self.filter_queryset(self.get_queryset())

        name = request.GET.get('name')
        type = request.GET.get('type')
        if name:
            queryset = queryset.filter(
                Q(username__icontains=name) | Q(company_name__icontains=name) | Q(title__icontains=name))
        if type:
            queryset = queryset.filter(
                Q(type=type))

        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(queryset, many=True)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
        return APIResponse(results=self.get_paginated_response(serializer.data).data)

    @action(methods=['post'], detail=False, url_path='by_user')
    def get_skus_by_user_id(self, request, *args, **kwargs):
        results = {}
        # 超级管理员
        if self.request.user.group_id == '1':
            queryset = self.queryset.filter()
        else:
            group_id = self.request.data['group_id']
            if group_id == '2':
                user_id = self.request.data['id']
                queryset = self.queryset.filter(user_id=user_id)
            else:
                company_id = self.request.data['company_id']
                queryset = self.queryset.filter(company_id=company_id)

        if len(queryset) > 0:
            serializer = self.get_serializer(queryset, many=True)
            skus = Skus.objects.filter(id=queryset[0].skus_id).values()
            results = {
                'list': serializer.data,
                'skus':skus
            }
        else:
            results = {
                'list': [],
                'skus': Skus.objects.filter(id=1).values(),
            }
        return VueAPIResponse(self, queryset, data=results)